//
//  HomeViewController.m
//  ZzzzyManProject
//
//  Created by mac on 16/2/24.
//  Copyright © 2016年 ZzzzyMan@. All rights reserved.
//

#import "HomeViewController.h"
#import "PageScrollView.h"
#import "HomeViewCell.h"
#import <AVOSCloud/AVOSCloud.h>
#import <AFNetworking.h>
#import "NewsModel.h"
#import "ZyProgressHUD.h"
#import <AVQuery.h>
#import <MJRefresh.h>

//左抽屉需要导入的头文件
#import "InfoViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "MMDrawerBarButtonItem.h"

@interface HomeViewController ()

@property (nonatomic,strong) NSMutableArray * newsModel;
@property (nonatomic,strong) UIActivityIndicatorView * indicatorView; //菊花
@property (nonatomic,assign) int rowNumber;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@",path);
    
    [self initUI];
    //左抽屉控制按钮方法
    [self setupLeftMeunButton];
    //检查网络状态
    [self reachabilityStatus];
    
    
}

#pragma mark - 刷新数据
- (void)loadData {
    AVQuery *query = [AVQuery queryWithClassName:@"MarvelNews"];
    [query getObjectInBackgroundWithId:@"56e0ec4fd342d3005405d954" block:^(AVObject *object, NSError *error) {
        
        NSDictionary * dict = (NSDictionary *)object;
        NSArray * tempArray = dict[@"news"];
        NSMutableArray * arrM = [[NSMutableArray alloc] initWithCapacity:tempArray.count];
        for (NSDictionary * tempDict in tempArray) {
            NewsModel * model = [NewsModel newsModelWithDict:tempDict];
            [arrM addObject:model];
        }
        
        if (object) {
            [self.newsModel addObjectsFromArray:arrM];
            [self.tableView reloadData];
            if (self.newsModel.count < 20) {
                [self.tableView.mj_footer endRefreshing];
            }
            
            if (self.newsModel.count > 20) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        else if (error) {
            NSLog(@"%@",error);
        }
        
        
    }];
    
}


#pragma mark - 检查网络状态
- (void)reachabilityStatus {
    
    AFNetworkReachabilityManager * manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusUnknown ||
            status == AFNetworkReachabilityStatusNotReachable) {
            //无网络提示
            ZyProgressHUD * hud = [ZyProgressHUD sharedHUD];
            hud.labelText = @"请检查网络";
            [self.view addSubview:hud];
            [hud showAnimated:YES whileExecutingBlock:^{
                sleep(2);
            } completionBlock:^{
                [hud removeFromSuperview];
            }];
        }
    }];
    
    [manager startMonitoring];
}

#pragma mark - 注册通知
// 设置本地通知
+ (void)registerLocalNotification:(NSInteger)alertTime {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];

    
    notification.fireDate = fireDate;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    notification.repeatInterval = NSCalendarUnitDay;
    
        NSLog(@"fireDate=%@",notification.fireDate);
    
    // 通知内容
    notification.alertBody =  @"通知测试";
    notification.alertTitle = @"ZzzzyMan提醒您通知测试成功";
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"测试" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitMonth;
    }
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

#pragma mark - 取消通知
+ (void)cancelLocalNotificationWithKey:(NSString *)key {
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            
            // 如果找到需要取消的通知，则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
            }
        }
    }
}

#pragma mark - 左抽屉控制按钮方法
- (void)setupLeftMeunButton {
    MMDrawerBarButtonItem * infoDrawerButton = [[MMDrawerBarButtonItem alloc] initWithTarget:self action:@selector(infoDrawerButton)];
    infoDrawerButton.image = [UIImage imageNamed:@"setUp"];
    
    self.navigationItem.leftBarButtonItem = infoDrawerButton;
    
}

#pragma mark - 抽屉按钮方法
- (void)infoDrawerButton {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}



#pragma mark - 初始化
- (void)initUI {
    
    //设置HeadView
    PageScrollView * pageScrollView = [[PageScrollView alloc] init];
    
    //设置上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }];
    
    //设置轮播器
    self.tableView.tableHeaderView = pageScrollView;
    
    //注册Cell
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier: @"HomeViewCell"];
    
}

#pragma mark - 自定义个人信息按钮

//- (void)customLeftBarButtonItem {
//    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
//    [btn setBackgroundImage:[UIImage imageNamed:@"setUp"] forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(information) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:btn];
//    self.navigationItem.leftBarButtonItem = item;
//    
//}

#pragma mark - 个人信息按钮监听事件
- (void)information {
    UITableViewController * tableVC = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    [self.navigationController pushViewController:tableVC animated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.newsModel.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeViewCell" forIndexPath:indexPath];
    cell.newsModel = self.newsModel[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsModel * newsModel = self.newsModel[indexPath.row];
    newsModel.isOpen = !newsModel.isOpen;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

#pragma mark - 懒加载数据
- (NSMutableArray *)newsModel {
    if (!_newsModel) {
        [NewsModel newsModelSuccessBlock:^(NSArray *array) {
            _newsModel = [NSMutableArray array];
            [_newsModel addObjectsFromArray:array];
            [self.tableView reloadData];
            
        } errorBlock:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
    return _newsModel;
}

#pragma mark - 上拉刷新的菊花
- (UIActivityIndicatorView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return _indicatorView;
}

@end
